package cn.lonecloud.study;

import cn.lonecloud.study.config.ZkConfig;
import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.locks.Lock;

/**
 * @author lonecloud
 * @version v1.0
 * @Package cn.lonecloud.study
 * @Description: TODO
 * @date 2018/5/23下午6:02
 */
public abstract class AbstractZkLock implements Lock,Watcher{

    protected ZooKeeper zooKeeper=null;

    Logger logger=LoggerFactory.getLogger(AbstractZkLock.class);
    /**
     * 定义根目录
     */
    private String rootPath="/zkLock";

    AbstractZkLock(ZkConfig zkConfig) throws IOException {
        //创建连接
        zooKeeper=new ZooKeeper(zkConfig.getConnectString(),zkConfig.getSessionTimeout(),this);
        try {
            //判断根节点是否存在
            if (zooKeeper.exists(rootPath,true)==null){
                //不存在则创建
                zooKeeper.create(rootPath,new byte[0],ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            }
        } catch (KeeperException | InterruptedException e) {
            logger.error("create node error",e);
        }
    }

    @Override
    public void unlock() {
        //解锁判断zk是否为Null
        if (zooKeeper!=null){
            try {
                //关闭zk
                zooKeeper.close();
            } catch (InterruptedException e) {
                logger.error("close zk error",e);
            }
        }
    }

}
